import React, { PureComponent } from 'react';
import { connect } from 'dva';

import {
  Avatar,
  List,
  Card,
  Button,
  Form,
  Input,
  Modal,
  Select,
  InputNumber,
  Popconfirm,
  Radio,
} from 'antd';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from './styles.less';

const { Item: FormItem } = Form;
const { Button: RadioButton, Group: RadioGroup } = Radio;
const ModelName = 'port';
const Option = Select.Option;

@connect(({ loading, port }) => ({
  loading: loading.effects[`${ModelName}`],
  model: port,
}))
@Form.create()
class Comp extends PureComponent {
  state = {
    visible: false,
    current: {},
    currentType: 1,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: `${ModelName}/get`,
    });
  }

  showModal = () => {
    this.setState({
      visible: true,
      current: undefined,
    });
  };

  showEditModal = item => {
    this.setState({
      visible: true,
      current: item,
    });
  };

  handleCancel = () => {
    this.setState({
      visible: false,
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    const { current } = this.state;
    const id = current ? current.id : 0;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const payload = {
        id,
        ...fieldsValue,
        objectName: fieldsValue.objectName.trim(),
      };
      dispatch({
        type: `${ModelName}/createOrUpdate`,
        payload: payload,
        callback: _ => {
          this.setState({ visible: false });
        },
      });
    });
  };

  deleteItem = id => {
    const { dispatch } = this.props;
    dispatch({
      type: `${ModelName}/remove`,
      payload: id,
    });
  };

  render() {
    const {
      model,
      loading,
      form: { getFieldDecorator },
    } = this.props;
    const { visible, current, currentType } = this.state;
    const { list } = model;

    const dSource = currentType > 0 ? list.filter(r => r.portType === currentType) : list;

    const editForm = () => {
      const formLayout = {
        labelCol: { span: 7 },
        wrapperCol: { span: 13 },
      };

      return (
        <Modal
          title={`${current ? '编辑' : '添加'}${model.title}`}
          className={styles.standardListForm}
          destroyOnClose
          visible={visible}
          onOk={this.handleSubmit}
          onCancel={this.handleCancel}
        >
          <Form onSubmit={this.handleSubmit}>
            <FormItem label="排序" {...formLayout}>
              {getFieldDecorator('sortIndex', {
                rules: [{ required: true, message: '请输入排序号' }],
                initialValue: current ? current.sortIndex : 0,
              })(<InputNumber />)}
            </FormItem>

            <FormItem label="名称" {...formLayout}>
              {getFieldDecorator('objectName', {
                rules: [{ required: true, message: '请输入名称' }],
                initialValue: current ? current.objectName : '',
              })(<Input placeholder="请输入" />)}
            </FormItem>

            <FormItem label="港口类型" {...formLayout}>
              {getFieldDecorator('portType', {
                rules: [{ required: true, message: '请输入港口类型' }],
                initialValue: current ? current.portType : 1,
              })(
                <Select>
                  {
                    [{ id: 1, objectName: '起运港' }, { id: 2, objectName: '目的港' }].map(item =>
                      <Option key={item.id} value={item.id} >{item.objectName}</Option>)
                  }
                </Select>
              )}
            </FormItem>

          </Form>
        </Modal>
      );
    };

    const dataList = () => {
      return (
        <div>
          <Button
            type="dashed"
            style={{ width: '100%', marginBottom: 8 }}
            icon="plus"
            onClick={this.showModal}
          >
            添加
          </Button>
          <List
            size="small"
            rowKey="id"
            loading={loading}
            dataSource={dSource}
            renderItem={(item, index) => (
              <List.Item
                actions={[
                  <Popconfirm title="确定要删除此项吗?" onConfirm={() => this.deleteItem(item.id)}>
                    <a>删除</a>
                  </Popconfirm>,
                ]}
              >
                <List.Item.Meta
                  avatar={
                    <Avatar style={{ backgroundColor: '#f56a00' }} shape="square" size="small">
                      {item.sortIndex}
                    </Avatar>
                  }
                  title={
                    <span>
                      <a
                        onClick={e => {
                          e.preventDefault();
                          this.showEditModal(item);
                        }}
                      >
                        {item.objectName}
                      </a>
                    </span>
                  }
                  description={item.portType === 1 ? '起运港' : item.portType === 2 ? '目的港' : '错误!!!'}
                />
              </List.Item>
            )}
          />
        </div>
      );
    };

    const extraContent = (
      <div className={styles.extraContent}>
        <RadioGroup
          defaultValue={currentType}
          onChange={e => {
            e.preventDefault();
            this.setState({ currentType: e.target.value });
          }}
        >
          <RadioButton value={0}>全部</RadioButton>
          <RadioButton value={1}>起运港</RadioButton>
          <RadioButton value={2}>目的港</RadioButton>
        </RadioGroup>
      </div>
    );

    return (
      <PageHeaderWrapper>
        <div className={styles.standardList}>
          <Card
            className={styles.listCard}
            bordered={false}
            title={model.title}
            extra={extraContent}
          >
            {dataList()}
          </Card>
        </div>
        {editForm()}
      </PageHeaderWrapper>
    );
  }
}

export default Comp;
